// 确保所有代码在 DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 初始化所有功能
    initSwitchTab();
    initEmojiPanel();
    initMessageInput();
    // 初始化头像上传
    // initAvatarUpload();
    // 初始化时获取用户信息
    getUserInfo();
    // 先加载会话列表
    getSessionList();
});

// WebSocket连接，带上token参数
let wsToken = localStorage.getItem("token");
let websocket = new WebSocket("ws://127.0.0.1:8080/webmessage?token=" + wsToken);

websocket.onopen = function () {
    console.log("成功");
}

websocket.onclose = function () {
    console.log("关闭");
}

websocket.onerror = function () {
    console.log("错误");
}

websocket.onmessage = function (e) {
    // 解析消息
    let msg = {};
    try {
        msg = JSON.parse(e.data);
    } catch (err) {
        console.log("消息解析失败", e.data);
        return;
    }
    if (msg.type === "message") {
        // 判断当前会话是否为该sessionId
        let currentSessionId = getCurrentSessionId();
        if (currentSessionId && msg.sessionId && msg.sessionId.toString() === currentSessionId.toString()) {
            let messageShowDiv = document.querySelector('.right .message-show');
            let selfUserName = localStorage.getItem("username") || document.querySelector('.left .user').textContent;
            addMessage(messageShowDiv, msg, selfUserName);
            messageShowDiv.scrollTop = messageShowDiv.scrollHeight;
        }
        // 实时更新会话列表最后一条消息
        updateSessionListLastMsg(msg.sessionId, msg.content);
    } else if (msg.type === 'friendRequest') {
        let req = msg.data;
        console.log('收到好友请求推送', req);
        Swal.fire({
            title: '好友请求',
            text: `用户${req.fromUserId}请求加你为好友，是否同意？`,
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: '同意',
            cancelButtonText: '拒绝'
        }).then((result) => {
            console.log('Swal 回调 result:', result);
            if (result.isConfirmed) {
                console.log('同意好友请求，requestId:', req.id);
                handleFriendRequest(req.id, 'accept');
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                console.log('拒绝好友请求，requestId:', req.id);
                handleFriendRequest(req.id, 'reject');
            }
        });
    } else if (msg.type === 'friendAccept') {
        Swal.fire('你和对方已互为好友，可以开始聊天！');
        getFriendList && getFriendList();
        getSessionList && getSessionList();
    }
}

// 封装切换标签图标的逻辑
function setTabIcons(isSessionTab) {
    const tabSession = document.querySelector('.tab .tab-session');
    const tabFriend = document.querySelector('.tab .tab-friend');
    if (isSessionTab) {
        tabSession.style.backgroundImage = 'url(pic/对话.png)';
        tabFriend.style.backgroundImage = 'url(pic/用户2.png)';
    } else {
        tabSession.style.backgroundImage = 'url(pic/对话2.png)';
        tabFriend.style.backgroundImage = 'url(pic/用户.png)';
    }
}

function initSwitchTab() {
    const tabSession = document.querySelector('.tab .tab-session');
    const tabFriend = document.querySelector('.tab .tab-friend');
    const lists = document.querySelectorAll('.list');

    tabSession.addEventListener('click', () => {
        setTabIcons(true);
        getSessionList();
        lists[0].classList.remove('hide');
        lists[1].classList.add('hide');
        $('#searchResult').empty();
    });

    tabFriend.addEventListener('click', () => {
        setTabIcons(false);
        getFriendList();
        lists[0].classList.add('hide');
        lists[1].classList.remove('hide');
        $('#searchResult').empty();
    });
}

// 表情面板功能
function initEmojiPanel() {
    const emojiBtn = document.querySelector('.emoji-btn');
    const emojiPanel = document.querySelector('.emoji-panel');
    const messageInput = document.querySelector('.message-input');

    // 元素存在性检查
    if (!emojiBtn || !emojiPanel || !messageInput) {
        console.error('表情相关元素未找到，请检查HTML结构');
        return;
    }

    // 点击表情按钮：切换面板显示
    emojiBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        emojiPanel.classList.toggle('hide');
    });

    // 点击表情：插入输入框并隐藏面板
    emojiPanel.addEventListener('click', (e) => {
        if (e.target.tagName === 'SPAN') {
            const cursorPos = messageInput.selectionStart;
            const text = messageInput.value;
            messageInput.value = text.slice(0, cursorPos) + e.target.textContent + text.slice(cursorPos);
            messageInput.selectionStart = messageInput.selectionEnd = cursorPos + e.target.textContent.length;
            updateButtonState();
            emojiPanel.classList.add('hide');
        }
    });

    // 点击页面其他区域：隐藏表情面板
    document.addEventListener('click', () => {
        emojiPanel.classList.add('hide');
    });
}

// 输入框和发送按钮功能
function initMessageInput() {
    const messageInput = document.querySelector('.message-input');
    const sendButton = document.querySelector('.ctrl button.send-btn');
    updateButtonState();
    messageInput.addEventListener('input', updateButtonState);
    sendButton.addEventListener('click', () => sendMessage(getCurrentSessionId()));
    messageInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey && getCurrentSessionId()) {
            e.preventDefault();
            sendMessage(getCurrentSessionId());
        }
    });
}

// 更新发送按钮状态
function updateButtonState() {
    const messageInput = document.querySelector('.message-input');
    const sendButton = document.querySelector('.ctrl button.send-btn');
    const hasContent = messageInput.value.trim().length > 0;

    if (hasContent) {
        sendButton.classList.add('active');
    } else {
        sendButton.classList.remove('active');
    }
}

// 获取当前选中的会话ID
function getCurrentSessionId() {
    const activeSession = document.querySelector('#session-list .session-item.highlight');
    return activeSession ? activeSession.getAttribute('message-session-id') : null;
}

// 获取用户信息
function getUserInfo() {
    $.ajax({
        type: "get",
        url: "/user/getuser?userId=" + localStorage.getItem("userId"),
        success: function (result) {
            if (result && result.code === "SUCCESS" && result.data) {
                const userInfo = result.data;
                $(".left .user").text(userInfo.username);
                // 新增：显示头像
                if (userInfo.avatar) {
                    document.querySelector('.avatar').src = userInfo.avatar;
                    localStorage.setItem('avatar', userInfo.avatar);
                } else {
                    document.querySelector('.avatar').src = '/avatar/default.png';
                    localStorage.setItem('avatar', '/avatar/default.png');
                }
            }
        },
        error: function () {
            console.log("获取用户信息错误");
        }
    });
}

// 完善好友列表点击事件处理
function getFriendList() {
    $.ajax({
        type: "get",
        url: "/friend/getFriendList?userId=" + localStorage.getItem("userId"),
        success: function (result) {
            if (result.code === "SUCCESS" && result.data && result.data.length > 0) {
                let finalHTML = "";
                result.data.forEach(friend => {
                    // 头像优先用avatar字段
                    let avatarUrl = friend.avatar || '/avatar/default.png';
                    finalHTML += '<li class="friend-item" data-friend-id="' + friend.friendId + '" style="display:flex;align-items:center;gap:10px;">';
                    finalHTML += '<img src="' + avatarUrl + '" style="width:32px;height:32px;border-radius:50%;object-fit:cover;">';
                    finalHTML += '<h4>' + friend.friendName + '</h4>';
                    finalHTML += '</li>';
                });
                $("#friend-list").html(finalHTML);

                // 先解绑，防止重复绑定
                $("#friend-list").off("click", ".friend-item");
                // 使用事件委托优化事件绑定
                $("#friend-list").on("click", ".friend-item", function () {
                    const friendId = $(this).data('friend-id');
                    const friendName = $(this).find('h4').text();

                    // 高亮当前选中的好友
                    $(this).addClass('highlight').siblings().removeClass('highlight');

                    // 查找会话是否已存在
                    const existingSession = findSessionByName(friendName);
                    const sessionListUL = document.querySelector('#session-list');

                    if (existingSession) {
                        // 存在则置顶并高亮
                        sessionListUL.insertBefore(existingSession, sessionListUL.firstChild);
                        // 切换到会话列表
                        switchToList('session');
                        // 高亮当前会话并加载消息
                        $(existingSession).addClass('highlight').siblings().removeClass('highlight');
                        loadSessionMessages(existingSession.getAttribute('message-session-id') || existingSession.getAttribute('data-message-session-id'), friendName);
                        return;
                    } else {
                        // 不存在则创建新会话
                        switchToList('session');
                        setTabIcons(true);
                        const newLi = document.createElement('li');
                        newLi.className = 'session-item';
                        newLi.innerHTML = '<h3>' + friendName + '</h3><p></p>';

                        // 插入到列表顶部
                        if (sessionListUL.firstChild) {
                            sessionListUL.insertBefore(newLi, sessionListUL.firstChild);
                        } else {
                            sessionListUL.appendChild(newLi);
                        }

                        // 发送请求到服务器创建会话
                        createSession(friendId, friendName, newLi);
                    }
                });
            }
        },
        error: function () {
            console.log("获取好友列表错误");
        }
    });
}

// 创建会话
function createSession(friendId, friendName, li) {
    $.ajax({
        type: "post",
        url: "/message/addMessageSession?toUserId=" + friendId + "&selfUserId=" + localStorage.getItem("userId"),
        success: function (result) {
            if (result.code === "SUCCESS" && result.data && result.data.sessionId) {
                // 检查会话 li 是否已存在
                let sessionListUL = document.querySelector('#session-list');
                let existingSession = document.querySelector(`#session-list .session-item[message-session-id="${result.data.sessionId}"]`)
                    || document.querySelector(`#session-list .session-item[data-message-session-id="${result.data.sessionId}"]`);
                if (existingSession) {
                    sessionListUL.insertBefore(existingSession, sessionListUL.firstChild);
                    $(existingSession).addClass('highlight').siblings().removeClass('highlight');
                    loadSessionMessages(result.data.sessionId, friendName);
                    document.querySelector('.right .title').textContent = friendName;
                    // 删除新建的 li
                    li.remove();
                    return;
                }
                li.setAttribute('message-session-id', result.data.sessionId);
                li.setAttribute('data-message-session-id', result.data.sessionId);
                switchToList('session');
                li.classList.add('highlight');
                loadSessionMessages(result.data.sessionId, friendName);
                document.querySelector('.right .title').textContent = friendName;
            }
        },
        error: function () {
            console.log("创建会话失败");
        }
    });
}

// 切换列表显示状态
function switchToList(listType) {
    const lists = document.querySelectorAll('.list');
    if (listType === 'friend') {
        lists[0].classList.add('hide');
        lists[1].classList.remove('hide');
    } else {
        lists[0].classList.remove('hide');
        lists[1].classList.add('hide');
    }
}

// 获取会话列表
function getSessionList() {
    $.ajax({
        type: "get",
        url: "/message/SessionList?userId=" + localStorage.getItem("userId"),
        success: function (result) {
            if (result.code === "SUCCESS" && result.data && result.data.length > 0) {
                let finalHTML = "";
                result.data.forEach(session => {
                    const lastMsg = session.lastMessage.length > 10
                        ? session.lastMessage.substring(0, 10) + '...'
                        : session.lastMessage;
                    // 头像优先用friends[0].avatar
                    let avatarUrl = (session.friends && session.friends[0] && session.friends[0].avatar) ? session.friends[0].avatar : '/avatar/default.png';
                    finalHTML += '<li class="session-item" message-session-id="' + session.sessionId + '" style="display:flex;align-items:center;gap:10px;">';
                    finalHTML += '<img src="' + avatarUrl + '" style="width:32px;height:32px;border-radius:50%;object-fit:cover;">';
                    finalHTML += '<div style="flex:1;">';
                    finalHTML += '<h3 style="margin:0;">' + session.friends[0].friendName + '</h3>';
                    finalHTML += '<p style="margin:0;color:#888;font-size:12px;">' + lastMsg + '</p>';
                    finalHTML += '</div>';
                    finalHTML += '</li>';
                });
                $("#session-list").html(finalHTML);

                // 先解绑，防止重复绑定
                $("#session-list").off("click", ".session-item");
                // 会话项点击事件 - 高亮并置顶
                $("#session-list").on("click", ".session-item", function () {
                    const sessionId = $(this).attr('message-session-id');
                    const friendName = $(this).find('h3').text();

                    // 高亮当前会话
                    $(this).addClass('highlight').siblings().removeClass('highlight');

                    // 置顶当前会话
                    const sessionListUL = document.querySelector('#session-list');
                    sessionListUL.insertBefore(this, sessionListUL.firstChild);

                    // 加载会话消息
                    loadSessionMessages(sessionId, friendName);
                });
                // 默认高亮并置顶第一个会话
                if ($("#session-list .session-item").length > 0) {
                    const firstSession = $("#session-list .session-item:first");
                    firstSession.addClass('highlight');
                    loadSessionMessages(firstSession.attr('message-session-id'), firstSession.find('h3').text());
                    document.querySelector('.right .title').textContent = firstSession.find('h3').text();
                }
            }
        },
        error: function () {
            console.log("获取会话列表错误");
        }
    });
}

// 查找会话
function findSessionByName(username) {
    const lis = document.querySelectorAll('#session-list>li');
    for (const li of lis) {
        const h3 = li.querySelector('h3');
        if (h3 && h3.innerHTML === username) {
            return li;
        }
    }
    return null;
}

// 加载会话消息
function loadSessionMessages(sessionId, friendName) {
    const titleDiv = document.querySelector('.right .title');
    const messageShowDiv = document.querySelector('.right .message-show');

    titleDiv.textContent = friendName;
    messageShowDiv.innerHTML = "";

    // 前端去重渲染
    $.ajax({
        type: 'get',
        url: '/message/getMessageBySessionId?sessionId=' + sessionId,
        success: function (result) {
            // 兼容直接数组或包装对象
            var data = Array.isArray(result) ? result : (result.data || []);
            if (data.length > 0) {
                const selfUserName = document.querySelector('.left .user').textContent;
                const renderedSet = new Set();
                data.forEach(message => {
                    const uniqueKey = message.messageId || (message.fromName + '|' + message.content);
                    if (!renderedSet.has(uniqueKey)) {
                        addMessage(messageShowDiv, message, selfUserName);
                        renderedSet.add(uniqueKey);
                    }
                });
                messageShowDiv.scrollTop = messageShowDiv.scrollHeight;
            }
        },
        error: function () {
            console.log("获取消息失败");
        }
    });
}

// 添加消息到界面（优化版）
function addMessage(messageShowDiv, message, selfUserName) {
    const messageDiv = document.createElement('div');
    let isSelf = (message.fromName === selfUserName) || (message.fromId && message.fromId == localStorage.getItem('userId'));
    messageDiv.className = 'message ' + (isSelf ? 'message-right' : 'message-left');
    let avatarUrl = '';
    if (isSelf) {
        avatarUrl = localStorage.getItem('avatar') || '/avatar/default.png';
    } else if (message.avatar) {
        avatarUrl = message.avatar;
    } else {
        avatarUrl = '/avatar/default.png';
    }
    messageDiv.innerHTML =
        `<img class="msg-avatar" src="${avatarUrl}" style="width:36px;height:36px;border-radius:50%;object-fit:cover;">
         <div style="display:flex;flex-direction:column;align-items:${isSelf ? 'flex-end' : 'flex-start'};flex:1;">
            <div class="user">${message.fromName || ''}</div>
            <div class="bubble">${message.content || ''}</div>
         </div>`;
    messageShowDiv.appendChild(messageDiv);
}

function sendMessage(sessionId) {
    const messageInput = document.querySelector('.message-input');
    const content = messageInput.value.trim();
    if (!content || !sessionId) return;
    const msg = {
        type: "message",
        sessionId: Number(sessionId),
        content: content
    };
    if (!websocket || websocket.readyState !== 1) {
        alert("消息通道未连接，请刷新页面重试");
        return;
    }
    websocket.send(JSON.stringify(msg));
    // 本地回显补全字段
    let messageShowDiv = document.querySelector('.right .message-show');
    let selfUserName = localStorage.getItem("username") || document.querySelector('.left .user').textContent;
    let selfUserId = localStorage.getItem("userId");
    addMessage(messageShowDiv, {
        fromName: selfUserName,
        fromId: selfUserId,
        sessionId: sessionId,
        content: content,
        messageType: 'text'
    }, selfUserName);
    messageShowDiv.scrollTop = messageShowDiv.scrollHeight;
    messageInput.value = "";
    updateButtonState();
}

// 新增：实时更新会话列表最后一条消息并置顶
function updateSessionListLastMsg(sessionId, content) {
    const sessionListUL = document.querySelector('#session-list');
    const sessionItems = sessionListUL.querySelectorAll('.session-item');
    let targetLi = null;
    sessionItems.forEach(li => {
        if (li.getAttribute('message-session-id') == sessionId) {
            targetLi = li;
        }
    });
    if (targetLi) {
        // 更新最后一条消息内容
        let p = targetLi.querySelector('p');
        if (!p) {
            p = document.createElement('p');
            targetLi.appendChild(p);
        }
        p.textContent = content.length > 10 ? content.substring(0, 10) + '...' : content;
        // 置顶该会话项
        sessionListUL.insertBefore(targetLi, sessionListUL.firstChild);
    }
}

// 搜索用户并判断是否为好友
function searchUser() {
    var keyword = $('#searchInput').val().trim();
    if (!keyword) return;
    var userId = localStorage.getItem('userId');
    console.log('开始搜索', keyword);
    $.ajax({
        url: '/user/search',
        data: { keyword: keyword },
        success: function (user) {
            console.log('searchUser返回', user);
            if (!user || user.code !== "SUCCESS" || !user.data) {
                $('#searchResult').html('<div style="color:#fff;">未找到该用户</div>');
                Swal.fire('未找到该用户');
                return;
            }
            var u = user.data;
            if (u.userId == userId) {
                $('#searchResult').html('<div style="color:#fff;">不能添加自己为好友</div>');
                Swal.fire('不能添加自己为好友');
                return;
            }
            $.get('/friend/isFriend', { userId: userId, friendId: u.userId }, function (isFriend) {
                console.log('isFriend结果', isFriend, typeof isFriend);
                if (isFriend === true || isFriend === "true" || isFriend === 1 || isFriend === "1") {
                    $('#searchResult').html('<div style="color:#fff;">你们已经是好友，点击左侧直接聊天</div>');
                    Swal.fire('你们已经是好友，直接跳转聊天');
                    // window.location.href = '/client.html?friendId=' + u.userId;
                } else {
                    $('#searchResult').html(
                        `<div style="display:flex;align-items:center;gap:10px;">
                            <img src="${u.avatar || '/avatar/default.png'}" style="width:32px;height:32px;border-radius:50%;object-fit:cover;">
                            <span>${u.username}</span>
                            <button class="add-friend-btn" data-id="${u.userId}">添加该好友</button>
                        </div>`
                    );
                    console.log('显示添加好友按钮', u);
                    $('.add-friend-btn').off('click').on('click', function () {
                        var toUserId = $(this).data('id');
                        var userId = localStorage.getItem('userId');
                        console.log('点击添加好友', { fromUserId: userId, toUserId: toUserId });
                        $.post('/friend/request/send', { fromUserId: userId, toUserId: toUserId }, function (res) {
                            Swal.fire('请求已发送');
                            $('#searchResult').empty();
                            getFriendList && getFriendList();
                        }).fail(function (xhr, status, error) {
                            Swal.fire('添加好友请求失败: ' + error);
                        });
                    });
                }
            }).fail(function (xhr, status, error) {
                $('#searchResult').html('<div style="color:#fff;">好友关系查询失败: ' + error + '</div>');
                console.error('isFriend接口失败', error);
            });
        },
        error: function (xhr, status, error) {
            $('#searchResult').html('<div style="color:#fff;">用户搜索接口异常: ' + error + '</div>');
            console.error('user/search接口异常', error);
        }
    });
}

// 事件绑定（只绑定一次）
$(document).off('click', '#searchBtn').on('click', '#searchBtn', searchUser);
$(document).off('keydown', '#searchInput').on('keydown', '#searchInput', function (e) { if (e.key === 'Enter') searchUser(); });

function handleFriendRequest(requestId, action) {
    console.log('handleFriendRequest 被调用', requestId, action);
    $.post('/friend/request/handle', { requestId: requestId, action: action }, function (res) {
        console.log('handleFriendRequest返回', res);
        // 修改成功/失败提示
        if (typeof res === 'string') {
            Swal.fire(res);
        } else if (res.code === 0) {
            Swal.fire(res.msg || '操作完成');
            if (action === 'accept') {
                getFriendList && getFriendList();
            }
        } else {
            Swal.fire(res.msg === '操作失败' ? '该请求已被处理或你们已经是好友' : (res.msg || '操作失败'));
        }
    }).fail(function (xhr, status, error) {
        Swal.fire('处理好友请求失败: ' + error);
        console.error('handleFriendRequest接口失败', error);
    });
}

// 页面加载时自动切换到指定好友
$(document).ready(function () {
    const urlParams = new URLSearchParams(window.location.search);
    const friendId = urlParams.get('friendId');
    if (friendId) {
        // 自动高亮好友并打开会话
        // 先切换到好友tab
        $(".tab-friend").click();
        setTimeout(function () {
            const $target = $(`#friend-list .friend-item[data-friend-id='${friendId}']`);
            if ($target.length) {
                $target.click();
            }
        }, 500); // 等待好友列表渲染
    }
});